package com.tdam2011.grupo02.ui;

import java.util.ArrayList;

import com.tdam2011.grupo02.R;
import com.tdam2011.grupo02.compatibility.ActionBarListActivity;
import com.tdam2011.grupo02.domain.ContactoSeleccionInfo;

import android.content.ContentUris;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class ContactoSeleccionListActivity extends ActionBarListActivity {

	private ContactoSeleccionInfoAdapter adapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.contacto_seleccion);

		if (getIntent().hasExtra("contactoId")) {
			final String idContacto = (String) ((Bundle) getIntent()
					.getExtras()).get("contactoId");

			Button btnLogs = (Button) findViewById(R.id.btnLogCS);
			btnLogs.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					Intent intent = new Intent(
							ContactoSeleccionListActivity.this,
							HistorialLogFragmentActivity.class);
					intent.putExtra("id", idContacto);
					startActivity(intent);
					overridePendingTransition(android.R.anim.fade_in,
							android.R.anim.fade_out);
				}

			});

			adapter = new ContactoSeleccionInfoAdapter();
			setListAdapter(adapter);

			String whereName = "(" + ContactsContract.Data.MIMETYPE
					+ " = ? OR " + ContactsContract.Data.MIMETYPE + " =? OR "
					+ ContactsContract.Data.MIMETYPE + " =? OR "
					+ ContactsContract.Data.MIMETYPE
					+ " =? ) AND CONTACT_ID = ?";
			String[] whereNameParams = new String[] {
					ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE,
					ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,
					ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE,
					ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE,
					idContacto };
			Cursor nameCur = getContentResolver().query(
					ContactsContract.Data.CONTENT_URI, null, whereName,
					whereNameParams,
					ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME);

			startManagingCursor(nameCur);
			nameCur.moveToFirst();

			do {
				if (nameCur
						.getString(
								nameCur.getColumnIndex(ContactsContract.Data.MIMETYPE))
						.equals(ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)) {
					ImageView foto = (ImageView) findViewById(R.id.imgvContacto);
					Uri person = ContentUris.withAppendedId(
							ContactsContract.Contacts.CONTENT_URI,
							Long.parseLong(idContacto));
					foto.setImageURI(Uri.withAppendedPath(person,
							ContactsContract.Contacts.Photo.CONTENT_DIRECTORY));
					break;
				}
			} while (nameCur.moveToNext());

			nameCur.moveToLast();

			TextView nombre = (TextView) findViewById(R.id.txtvNombreC);
			nombre.setText(nameCur.getString(nameCur
					.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME)));

			TextView apellido = (TextView) findViewById(R.id.txtvApellido);
			apellido.setText(nameCur.getString(nameCur
					.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME)));

			setTitle(nombre.getText()+" "+apellido.getText());
			
			nameCur.moveToFirst();
			ContactoSeleccionInfo info;

			do {
				if (nameCur
						.getString(
								nameCur.getColumnIndex(ContactsContract.Data.MIMETYPE))
						.equals(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)) {
					info = new ContactoSeleccionInfo();
					info.setDato(nameCur.getString(nameCur
							.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
					int type = nameCur
							.getInt(nameCur
									.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
					info.setTipo(type);
					String label = null;
					if (type == Phone.TYPE_CUSTOM) {
						label = nameCur
								.getString(nameCur
										.getColumnIndex(ContactsContract.CommonDataKinds.Phone.LABEL));
					}
					CharSequence phoneType = ContactsContract.CommonDataKinds.Phone
							.getTypeLabel(getResources(), type, label);
					info.setTxtTipo(phoneType.toString());
					info.setTelMail(0);
					adapter.addContactoSeleccionInfo(info);
				}
			} while (nameCur.moveToNext());

			nameCur.moveToFirst();

			do {
				if (nameCur
						.getString(
								nameCur.getColumnIndex(ContactsContract.Data.MIMETYPE))
						.equals(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)) {
					info = new ContactoSeleccionInfo();
					info.setDato(nameCur.getString(nameCur
							.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA1)));
					int type = nameCur
							.getInt(nameCur
									.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
					String label = null;
					info.setTipo(type);
					if (type == Email.TYPE_CUSTOM) {
						label = nameCur
								.getString(nameCur
										.getColumnIndex(ContactsContract.CommonDataKinds.Email.LABEL));
					}
					CharSequence emailType = ContactsContract.CommonDataKinds.Email
							.getTypeLabel(getResources(), type, label);
					info.setTxtTipo(emailType.toString());
					info.setTelMail(1);
					adapter.addContactoSeleccionInfo(info);
				}
			} while (nameCur.moveToNext());
			adapter.notifyDataSetChanged();
		}
	}

	@Override
	public void onListItemClick(ListView parent, View v, int position, long id) {
		TextView dato = (TextView) v.findViewById(R.id.txtvDato);

		if (Integer.parseInt(dato.getTag().toString()) == 0) {
			Intent callIntent = new Intent(Intent.ACTION_CALL);
			callIntent.setData(Uri.parse("tel:" + dato.getText()));
			startActivity(callIntent);
		} else {
			Uri uri = Uri.parse("mailto:" + dato.getText());
			Intent it = new Intent(Intent.ACTION_SENDTO, uri);
			startActivity(it);
		}
	}

	@Override
	public void overridePendingTransition(int enterAnim, int exitAnim) {
		super.overridePendingTransition(enterAnim, exitAnim);
	}

	class ContactoSeleccionInfoAdapter extends BaseAdapter {
		private ArrayList<ContactoSeleccionInfo> contactoSeleccionInfos;
		private LayoutInflater inflater;

		public ContactoSeleccionInfoAdapter() {
			contactoSeleccionInfos = new ArrayList<ContactoSeleccionInfo>();
			inflater = LayoutInflater.from(ContactoSeleccionListActivity.this);
		}

		public void addContactoSeleccionInfo(ContactoSeleccionInfo info) {
			if (info != null) {
				contactoSeleccionInfos.add(info);
			}
		}

		@Override
		public int getCount() {
			return contactoSeleccionInfos.size();
		}

		@Override
		public Object getItem(int position) {
			return contactoSeleccionInfos.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		class Holder {
			private ImageView imgvTipo;
			private TextView txtvTipo;
			private TextView txtvDato;
			private ImageView imgbOpcion1;
			private ImageView imgbOpcion2;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup arg2) {
			Holder holder;
			if (convertView == null) {
				convertView = inflater.inflate(
						R.layout.item_contacto_seleccion, null);
				holder = new Holder();
				holder.imgvTipo = (ImageView) convertView
						.findViewById(R.id.imgvTipo);
				holder.txtvTipo = (TextView) convertView
						.findViewById(R.id.txtvTipo);
				holder.txtvDato = (TextView) convertView
						.findViewById(R.id.txtvDato);
				holder.imgbOpcion1 = (ImageView) convertView
						.findViewById(R.id.imgbAccion1);
				holder.imgbOpcion2 = (ImageView) convertView
						.findViewById(R.id.imgbAccion2);
				convertView.setTag(holder);
			} else {
				holder = (Holder) convertView.getTag();
			}
			ContactoSeleccionInfo info = (ContactoSeleccionInfo) getItem(position);
			if (info.getTipo() != -1) {
				if (info.getTipo() == Phone.TYPE_HOME
						|| info.getTipo() == Email.TYPE_HOME)
					holder.imgvTipo.setImageResource(R.drawable.home_type);
				else if (info.getTipo() == Phone.TYPE_MOBILE
						|| info.getTipo() == Email.TYPE_MOBILE)
					holder.imgvTipo.setImageResource(R.drawable.mobile_type);
				else if (info.getTipo() == Phone.TYPE_WORK
						|| info.getTipo() == Email.TYPE_WORK)
					holder.imgvTipo.setImageResource(R.drawable.work_type);
				else if (info.getTipo() == Phone.TYPE_OTHER
						|| info.getTipo() == Email.TYPE_OTHER)
					holder.imgvTipo.setImageResource(R.drawable.other_type);
				else
					holder.imgvTipo.setImageResource(R.drawable.icon);
			} else
				holder.imgvTipo.setImageResource(R.drawable.icon);
			if (info.getTxtTipo() != null)
				holder.txtvTipo.setText(info.getTxtTipo());
			holder.txtvDato.setText(info.getDato());
			if (info.getTelMail() == 0) {
				holder.txtvDato.setTag(0);
				holder.imgbOpcion2.setVisibility(View.VISIBLE);
				holder.imgbOpcion2
						.setImageResource(android.R.drawable.sym_action_chat);
				holder.imgbOpcion2.setTag(info.getDato());
				holder.imgbOpcion2.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						Intent intent = new Intent(Intent.ACTION_VIEW);
						intent.setType("vnd.android-dir/mms-sms");
						intent.setData(Uri.parse("smsto:" + v.getTag()));
						startActivity(intent);
					}
				});
				holder.imgbOpcion1
						.setImageResource(android.R.drawable.sym_action_call);
			} else {
				holder.txtvDato.setTag(1);
				holder.imgbOpcion2.setVisibility(View.GONE);
				holder.imgbOpcion1
						.setImageResource(android.R.drawable.sym_action_email);
			}
			return convertView;
		}

	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Intent intent = null;
		switch (item.getItemId()) {
		case android.R.id.home:
			intent = new Intent(this, MainActivity.class);
			startActivity(intent);
			break;
		}

		return super.onOptionsItemSelected(item);
	}
}
